var entities = [];
var entity = {};
var entityInit = {};
var entityUpdate = {};

var invoiceBase = {};

var INVOICE_NO = 'MNS2009041';

/**
 * 1ページあたりの最大明細行数
 */
var MAX_ORDER_PER_INVOICE = 3;

var KEY = {
    MEISAI     : 'order',
    REVISION   : 'revision',
    INVOICE_NO : 'invoiceNo',
    ID         : 'id',
    DELETED    : 'deleted'
}

//_forでinsertBeforeされたTR行を判別するためのidにつかう接頭辞
var PREFIX_TR_INSERTED = 'tr_inserted_';


var HTTP_STATUS_CODE = {
    PUT_OK    : 200, //OK
    PUT_NG    : 409, //Conflict
    POST_OK   : 201, //Created
    POST_NG   : 409, //Conflict
    GET_OK    : 200, //OK
    GET_NG    : 204, //No Content
    DELETE_OK : 200, //OK
    DELETE_NG : 304  //Not Modified
}

var common = {
    url : '/invoice'
};

function getRandomRGB() {
	var rgb = Math.floor(Math.random() * 0xFFFFFF).toString(16);
	for(count = rgb.length; count < 6; count++){
		rgb = "0" + rgb;
	}

	rgb = "#" + rgb;   
    return rgb;
}

function trim(val) {
    return val.replace(/(^&nbsp;)|(^\s*)|(\s*$)/g, '');  
}

function getDefaultJson(invoiceNo) {

	var entity = { invoice : { revision : 0, deleted : 0, id : 1, title : "御請求書", invoiceNo : invoiceNo, issuedDate : "2009/XX/XX", myCompanyName : "有限会社バーチャルテクノロジー", zip : "105-0055", address : "東京都港区芝1-2-3", phone : "031232222", companyName : "株式会社　ＸＸＸＸＸＸ", summary : "下記の通り御請求申し上げます。", invoiceTitle : "御請求金額", total : 0, job : "タイトル", seqno : "No", description : "品名", quantity : "数量", unitPrice : "単価（円）", lineTotal : "金額（円）", order : [{invoiceNo : invoiceNo,seqno : "1",productcd : "品名1",quantity : "0",unitPrice : "0",lineTotal : "0",deleted : 0},{invoiceNo : invoiceNo,seqno : "2",productcd : "品名2", quantity : "0", unitPrice : "0", lineTotal : "0", deleted : 0},{ invoiceNo : invoiceNo, seqno : "3", productcd : "品名3", quantity : "0", unitPrice : "0", lineTotal : "0", deleted : 0},{ invoiceNo : invoiceNo, seqno : "4", productcd : "品名4", quantity : "0", unitPrice : "0", lineTotal : "0", deleted : 0},{ invoiceNo : invoiceNo, seqno : "5", productcd : "品名5", quantity : "0", unitPrice : "0", lineTotal : "0", deleted : 0},{ invoiceNo : invoiceNo, seqno : "6", productcd : "品名6", quantity : "0", unitPrice : "0", lineTotal : "0", deleted : 0},{ invoiceNo : invoiceNo, seqno : "7",productcd : "品名7", quantity : "0",unitPrice : "0",lineTotal : "0",deleted : 0}],subtotal : "合計",subtotal1 : "0",salestax : "消費税",salestax1 : "0",totalTd : "御請求金額",totalTd1 : "0",note : "備考",note1 : "①　お支払日：2008年X月末日までにお支払いください。",note2 : "②　お振り込みの際は、下記口座にお願い致します。手数料は貴社にてご負担願います。",note3 : "③　振込先：バーチャル銀行芝町支店普通預金２０１２３４５〔口座名　有限会社バーチャルテクノロジー〕"}};

    return entity;
}


function eventListner(id) {

 		var token = id.split("-");
        
		if (token.length > 2) {
		
	        var element = document.getElementById('order-'+token[1]+'-'+token[2]);

			if ((token[1]=='quantity')||(token[1]=='unitPrice')) {
				element.innerHTML = encommas(element.innerHTML);
		        entity['invoice'][token[0]][(eval(token[2])-1)][token[1]] = element.innerHTML;
                var quantity = decommas(entity['invoice'][token[0]][(eval(token[2])-1)]['quantity']);
                var unitPrice = decommas(entity['invoice'][token[0]][(eval(token[2])-1)]['unitPrice']);
            }else {
		        entity['invoice'][token[0]][(eval(token[2])-1)][token[1]] = element.innerHTML;
            }
            
            var lineTotal = eval(quantity) * eval(unitPrice);
            entity['invoice'][token[0]][(eval(token[2])-1)]['lineTotal'] = encommas(lineTotal);
	        var element = document.getElementById('order-lineTotal-'+token[2]);

	        if (lineTotal.toString()!='NaN') {
            	element.innerHTML = encommas(lineTotal);
            	element.style.color ='black';
			}

			var total =0;
			for (var i in entity['invoice']['order']) {
				lineTotal = eval(decommas(entity['invoice']['order'][i]['lineTotal']));
		        if (lineTotal.toString()!='NaN') {
					total += lineTotal;
		        }
			}

	        var subtotal1 = document.getElementById('subtotal1');
	        var salestax1 = document.getElementById('salestax1');
	        var totalTd0 = document.getElementById('total');
	        var totalTd1 = document.getElementById('totalTd1');

	        if (total.toString()!='NaN') {
	            entity['invoice']['subtotal1'] = encommas(total);
            	subtotal1.innerHTML = encommas(total);
            	subtotal1.style.color ='black';
	            entity['invoice']['salestax1'] = encommas(Math.round(total*0.05));
            	salestax1.innerHTML = encommas(Math.round(total*0.05));
            	salestax1.style.color ='black';
	            entity['invoice']['total'] = encommas(Math.round(total*1.05));
            	totalTd0.innerHTML = encommas(Math.round(total*1.05));
            	totalTd0.style.color ='black';
	            entity['invoice']['totalTd1'] = encommas(Math.round(total*1.05));
            	totalTd1.innerHTML = encommas(Math.round(total*1.05));
            	totalTd1.style.color ='black';
			}

        }else {
                element.innerHTML = entity['invoice'][id];
        }

	

}

// カンマを付加した文字列を返す
function encommas (value) {
    return String (value).replace (/((?:^[-+])?\d{1,3})(?=(?:\d\d\d)+(?!\d))/g, '$1,');
}

// カンマを外した文字列を返す
function decommas (value) {
    return value.replace (/,/g, '');
}


